package com.maggie.demo.bootmongo.controller;

import com.maggie.demo.bootmongo.pojo.City;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by gmwang on 2022/6/2
 */
@RestController
public class MongoController {
    @Autowired
    private MongoTemplate mongoTemplate;

    @GetMapping("/test2")
    public void queryDemo(){
        System.out.println("=============查询所有====================");
        List<City> all = mongoTemplate.findAll(City.class);
        all.forEach(System.out::println);//方法引用
        System.out.println();

        System.out.println("===============条件查询=======================");
        //regex传正则表达式  查询sex为1并且name中包含zzj的用户
        String name="北京";
        Query query = new Query(Criteria.where("name").is(name));
        List<City> users = mongoTemplate.find(query, City.class);
        users.forEach(System.out::println);
        System.out.println();

        System.out.println("===============分页查询=======================");
        int pageSize=5,currentPage=1;
        long count = mongoTemplate.count(new Query(), City.class);
        List<City> userList = mongoTemplate.find(new Query().skip((currentPage - 1) * pageSize).limit(pageSize), City.class);
        System.out.println("记录数 = "+count);
        userList.forEach(System.out::println);
    }

}
